package com.huixi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huixi.Enums.VerifyTypeEnum;
import com.huixi.entity.User;
import com.huixi.service.UserService;
import com.huixi.service.mapper.UserMapper;
import com.huixi.utils.CodecUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author auto generator
 * @since 2019-05-27
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Transactional(isolation = Isolation.READ_COMMITTED, readOnly = true)
    @Override
    public User queryUser(String username, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            return null;
        }

        boolean passwordConfirm = CodecUtils.passwordConfirm(username + password, user.getPassword());
        if (BooleanUtils.isFalse(passwordConfirm)) {
            return null;
        }

        return user;
    }

    @Transactional(isolation = Isolation.READ_COMMITTED)
    @Override
    public boolean register(User user, String code) {
        String encodePassword = CodecUtils.passwordBcryptEncode(user.getUsername().trim(),
                user.getPassword().trim());
        user.setPassword(encodePassword);
        //插入数据库
        userMapper.insert(user);
        return true;
    }


    @Transactional(isolation = Isolation.READ_COMMITTED, readOnly = true)
    @Override
    public Boolean existUser(String verifyCode, String type) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (VerifyTypeEnum.USERNAME.getCode().equals(type)) {
            queryWrapper.eq("username", verifyCode);
        } else {
            queryWrapper.eq("phone", verifyCode);
        }

        User user = userMapper.selectOne(queryWrapper);
        return user != null;
    }

    @Transactional(isolation = Isolation.READ_COMMITTED)
    @Override
    public void registerUser(User user) {
        String encodePassword = CodecUtils.passwordBcryptEncode(user.getUsername().trim(),
                user.getPassword().trim());
        user.setPassword(encodePassword);
        user.setCreated(new Date());
        user.setUpdated(new Date());
        userMapper.insert(user);
    }
}
